package com.jiang.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jiang.common.constant.AuthServerConstant;
import com.jiang.common.to.SocialUser;
import com.jiang.common.utils.HttpUtils;
import com.jiang.common.utils.R;
import com.jiang.mall.auth.feign.MemberFeignService;
import com.jiang.common.to.MemberRespEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * 处理社交登录请求
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo (@RequestParam("code") String code, HttpSession session) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id", "3389462075");
        map.put("client_secret", "dca9fb296dae84c76eb12430b7b506a2");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);
        // 1.根据 code 换取 accessToken
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "response", new HashMap<>(), new HashMap<>(), map);
        // 2.处理
        if(response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            R r = memberFeignService.oauth2Login(socialUser);
            if(r.getCode() == 0) {
                MemberRespEntity memberRespEntity = r.getData("memberEntity", new TypeReference<MemberRespEntity>() {
                });
                log.info("登陆成功，用户：{}", memberRespEntity);
                session.setAttribute(AuthServerConstant.lOGIN_USER, memberRespEntity);
                // 登陆成功跳转回首页
                return  "redirect:http://gulimall.com";
            }else {
                return  "redirect:http://auth.gulimall.com/login.html";
            }
        }else  {
            return  "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
